package router

import (
	"52home/pkg/utils"
	"errors"
	"fmt"
	"github.com/go-playground/validator/v10"

	"net/http"

	"github.com/gin-gonic/gin"
)

// LoginForm 定义接收数据的结构体
type LoginForm struct {
	// binding:"required"修饰的字段，若接收为空值，则报错，是必须字段
	User     string `form:"username" json:"user" uri:"user" xml:"user" binding:"required"`
	Password string `form:"password" json:"password" uri:"password" xml:"password" binding:"required"`
}

// RegisterUserRouter user模块路由
func RegisterUserRouter(g *gin.RouterGroup) {

	// api param 路径参数
	// http://localhost:8000/user/arvin/52home.html
	// name: arvin
	// action: 52home.html
	g.GET("/:name/*action", func(c *gin.Context) {
		name := c.Param("name")
		action := c.Param("action")
		c.JSON(http.StatusOK, gin.H{
			"message": fmt.Sprintf("name: %s, action: %s", name, action),
		})
	})

	// url 查询参数
	// http://localhost:8000/?name=lili
	g.GET("/", func(c *gin.Context) {
		name := c.DefaultQuery("name", "arvin")
		c.String(http.StatusOK, fmt.Sprintf("name: %s", name))
	})

	g.GET("/login", func(c *gin.Context) {
		c.HTML(http.StatusOK, "user/login.html", nil)
	})

	// 直接解析表单
	//g.POST("/login", func(c *gin.Context) {
	//	username := c.DefaultPostForm("username", "shadow")
	//	password := c.DefaultPostForm("password", "123456")
	//	c.JSON(http.StatusOK, gin.H{
	//		"username": username,
	//		"password": password,
	//	})
	//})

	// 绑定表单到struct
	g.POST("/login", func(c *gin.Context) {
		// 声明接收的变量
		var form LoginForm
		// Bind()默认解析并绑定form格式
		// 根据请求头中content-type自动推断
		if err := c.ShouldBind(&form); err != nil {
			var errs validator.ValidationErrors
			ok := errors.As(err, &errs)
			if !ok {
				c.JSON(http.StatusOK, gin.H{
					"msg": err.Error(),
				})
			}
			c.JSON(http.StatusBadRequest, gin.H{
				"error": utils.RemoveTopStruct(errs.Translate(utils.GetTrans())),
			})
			return
		}
		// 判断用户名密码是否正确
		if form.User != "root" || form.Password != "admin" {
			c.JSON(http.StatusBadRequest, gin.H{"status": "304"})
			return
		}
		c.JSON(http.StatusOK, gin.H{"status": "200"})
	})
}
